var layerLoad;

/**
 * 页面初始化加载
 */
(function(){
    initProductList(1);
    $.ajax({
        url : $api.productCategory.selectProductCategorys,
        type : "GET",
        dataType : "JSON",
        contentType : 'application/json',
        beforeSend : function () {
            layerLoad = layer.load();
        },
        success : function(data) {
            var productCategoryTxt="";
            $.each(data.msg,function(index,data){
                productCategoryTxt+="<option value='"+data.id+"'>"+data.name+"</option>";
            });
            $("#categoryName").html(productCategoryTxt);
        },
        error : function() {
            layer.close(layerLoad);
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });
})();
function initProductList(currentPage) {
    $.ajax({
        url: $api.product.selectProducts,
        type: "POST",
        dataType: "JSON",
        contentType: 'application/json',
        data: JSON.stringify({"currentPage": currentPage}),
        beforeSend: function () {
            layerLoad = layer.load();
        },
        success: function (data) {
            if (!$checkRemouteStatus(data)) {
                layer.close(layerLoad);
                return;
            }
            layui.use('laytpl', function () {
                var laytpl = layui.laytpl;
                laytpl(sysProductListTpl.innerHTML).render(data, function (html) {
                    $('#sys-product-list-body').html(html);
                });
            });
            layui.use('laypage', function () {
                layui.laypage({
                    cont: $('#sys-product-list-body-page'),
                    pages: data.totalPage,
                    groups: 2,
                    curr: data.currentPage,
                    skip: true,
                    skin:'#0e90d2',
                    jump: function (obj, first) {
                        if (!first) {
                            initProductList(obj.curr);
                        }
                    }
                });
            });
            layer.close(layerLoad);
        },
        error: function () {
            layer.close(layerLoad);
            layer.msg('网络异常，请稍后再试', {icon: 2});
        }
    });
};
/*搜索*/
$('#sys-product-form-list-search').submit(function(e){
    e.preventDefault();
    initOrderList(1);
});
/*编辑*/
var product="";
var productId="";
function edit(othis){
    $("#sys-goods-list").collapse('close');
    $("#sys-product-update-model").css("display","block");
    product="selectProductById";
    productId=$(othis).attr("productId");
    $.ajax({
        url: $api.product[product] + "?productId=" + $(othis).attr("productId"),
        type: "GET",
        dataType: "JSON",
        contentType : 'application/json',
        beforeSend: function () {
            layerLoad = layer.load();
        },
        success: function (data) {
            layer.close(layerLoad);
            var dataObj=data.msg;
            if(data.code == '111111'){
                layer.msg(data.msg, {icon: 2});
            }else{
				/*数据回显*/
                $("#name").val(dataObj.name);
                $("#englishName").val(dataObj.englishName);
                $("#categoryName option").each(function(index,dom){
                    if(dataObj.categoryName==$(dom).text()){
                        $(dom).attr("selected",true);
                    }else{
                        $(dom).removeAttr("selected");
                    }
                });
                $("#productUnitName").val(dataObj.productUnitName);
                $("#product-id").val(dataObj.productId);
                $("#cost").val(dataObj.cost);
                //$("#point").val(dataObj.point);
                var isMarketable="0";
                dataObj.isMarketable ? isMarketable="1":isMarketable="0";
                $("#isMarketable").val(isMarketable);
                $("#sendTimeIntro").val(dataObj.sendTimeIntro);
                $("#sendIntro").val(dataObj.sendIntro);
                $("#announcement").val(dataObj.announcement);
                $("#foodStorage").val(dataObj.foodStorage);
                $("#sn").val(dataObj.sn);
                var productDetailsIntroduction=dataObj.productDetailsIntroduction.split("===");
                $("#productDetailsIntroduction").val(productDetailsIntroduction[0]);
                $("#productDetailsIntroduction2").val(productDetailsIntroduction[1]);
                $("#specification-id").val(dataObj.specificationId);
                $("#isCake").val(dataObj.isCake);
                /*商品*/
                var productImgTxt="";
                $.each(dataObj.productImages,function(index,data){
                    productImgTxt+="<div class='am-u-sm-4 am-margin-bottom-xs'><img class='am-thumbnail' flagImg="+data.product+" src="+data.thumbnail+" alt=''/>";
                    productImgTxt+="<a href='javascript:void(0)' onclick='delImg(this)' class='am-close am-close-alt am-icon-times'></a></div>";
                });
                $("#product-images2").html(productImgTxt);
                /*首页*/
                var  productImgTxt2="";
                productImgTxt2+="<div class='am-u-sm-4 am-margin-bottom-xs'><img class='am-thumbnail' src="+dataObj.thumbnailImage+" alt=''/>";
                productImgTxt2+="<a href='javascript:void(0)' onclick='delImg(this)' class='am-close am-close-alt am-icon-times'></a></div>";
                $("#product-images").html(productImgTxt2);
                layui.use('laytpl', function() {
                    var laytpl = layui.laytpl;
                    laytpl(sysSpecificationValuesListTpl.innerHTML).render(dataObj, function(html) {
                        $('#specProduct').html(html);
                    });
                });
            }
        },
        error: function () {
            layer.msg("网络开小差啦", {icon: 2});
        }
    });
};
/*保存*/
$("#save").click(function(){
    var  productImgArr=[];
	/*必填验证*/
    var ajaxFlag=1;
    $('#sys-product-update-model input[required="required"]').each(function(index,dom){
        if($(dom).val()===""){
            $(dom).addClass("am-field-error");
            layer.msg("数据填写不完整，请检查", {icon: 2});
            ajaxFlag=0;
            return
        }
    });
    if($("#specProduct tr").length < 1){
        layer.msg("至少要有一个规格", {icon: 2});
        return;
    }
    if($("#product-images img").length < 1){
        layer.msg("首页商品缩略图至少1张", {icon: 2});
        return;
    }
    if($("#product-images2 img").length < 1){
        layer.msg("商品详情页banner至少1张", {icon: 2});
        return;
    }
    if($("#product-images img").length>1){
        layer.msg("首页商品缩略图仅支持1张", {icon: 2});
        return false;
    }
    if($("#product-images2 img").length>5){
        layer.msg("商品详情页banner不得超过5张", {icon: 2});
        return false;
    }
    $(".priceLimit").each(function(index,damo){
        if(parseInt($(damo).val())>20000){
            layer.msg("价格不大于20000", {icon: 2});
            ajaxFlag==0;
        }
    });
    if(ajaxFlag==0){
        return
    }
    var productData={};
    $("#sys-product-form-update  .am-form-group > input").each(function(index,dom){
        if($(dom).attr("id")!==undefined){
            productData[$(dom).attr("id")]=$(dom).val();
        }
    });
    productData["name"]=$("#name").val();
    productData["englishName"]=$("#englishName").val();
    productData["productCategory"]=$("#categoryName").val();
    productData["isCake"]=$("#isCake").val();
    productData["isMarketableFlag"]=$("#isMarketable").val();
    productData["sendTimeIntro"]=$("#sendTimeIntro").val();
    productData["cost"]=$("#cost").val();
    productData["sendIntro"]=$("#sendIntro").val();
    productData["announcement"]=$("#announcement").val();
    productData["foodStorage"]=$("#foodStorage").val();
    productData["point"]=0;
    productData["sn"]=$("#sn").val();
    productData["productDetailsIntroduction"]=$("#productDetailsIntroduction").val()+"==="+$("#productDetailsIntroduction2").val();
    productData["productUnitName"]=$("#productUnitName").val();
    productData["productId"] = $("#product-id").val();
    productData["specificationId"] = $("#specification-id").val();
	/*规格列表list*/
    var specArr=[];
    $("#specProduct tr").each(function(specIndex,specDom){
        var specObj={};
        $(specDom).find("input").each(function(trIndex,trDom){
            if($(trDom).attr("name")!==undefined){
                specObj[$(trDom).attr("name")]=$(trDom).val();
            }
        });
        specObj["specificationValueId"] = $(specDom).attr("specificationValueId");
        specArr.push(specObj);
    });
	/*图片list*/
    $("#product-images2 img").each(function(index,damo){
        var productImgObj={};
        productImgObj["isNew"]=$(damo).attr("flagImg");
        productImgObj["base64String"]=$(damo).attr("src");
        productImgArr.push(productImgObj);
    });
    productData["base64ImageBeans"]=productImgArr;
    productData["thumbnailBase64Image"]=$("#product-images img").attr("src");
    productData["specificationValues"]=specArr;
    $.ajax({
        url: $api.product.insertOrUpdateProduct,
        type: "POST",
        dataType: "JSON",
        contentType : 'application/json',
        data :  JSON.stringify(productData) ,
        beforeSend: function () {
            layerLoad = layer.load();
        },
        success: function (data) {
            layer.close(layerLoad);
            var dataObj=data.msg;
            if(data.code == '111111'){
                layer.msg(data.msg, {icon: 2});
            }else{
                layer.msg(data.msg, {icon: 1});
                $("#product-images").html("");
                initProductList(1);
                resetInput();
                $("#sys-product-update-model").css("display","none");
                $("#sys-goods-list").collapse('open');
            }
        },
        error: function () {
            layer.close(layerLoad);
            layer.msg("网络开小差啦", {icon: 2});
        }
    });
});
/*删除规格*/
$("#specProduct").on("click",".deletProduct",function(){
    $(this).parent().parent().parent().remove();
});
/*新增规格*/
var goodsTxt="<tr><td class='am-text-truncate am-tab-width-min'><input  type='number' min='0' class='isPositive am-form-field am-radius' required='required' name='productUnitNumber' value='' placeholder='仅支持数字' /></td>";
goodsTxt+="<td class='am-text-truncate am-tab-width-min'><input type='text' class='am-form-field am-radius' name='productSize' value='' placeholder='尺寸说明' /></td>";
goodsTxt+="<td class='am-text-truncate am-tab-width-min'><input type='text' class='am-form-field am-radius' name='productSpecificationIntroduction' value='' placeholder='介绍' /></td>";
goodsTxt+="<td class='am-text-truncate am-tab-width-min'><input type='text' class='isPrice am-form-field am-radius' name='productPrice' required='required' value='' placeholder='价格' /></td>";
goodsTxt+="<td class='am-text-truncate am-edit-width-min'><div class='am-btn-group am-btn-group-xs'><input type='button' class='am-btn am-btn-success btn-order-list-detail deletProduct'  value='删除'>";
goodsTxt+="</div></td></tr>";
$("#addGoods").click(function(){
    $("#specProduct").append(goodsTxt);
});
/*图片转64*/
window.onload = function(){
    var input = document.getElementById("productFileImg");
    var input2 = document.getElementById("productFileImg2");
    if ( typeof(FileReader) === 'undefined' ){
        layer.msg("抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！", {icon: 2});
        input.setAttribute( 'disabled','disabled' );
    } else {
        input.addEventListener( 'change',readFile,false );
        input2.addEventListener( 'change',readFile,false );
    }
};
function readFile(){
    var domText="";
    if($(this).attr("id")==="productFileImg2"){
        domText="#product-images2";
    }else{
        domText="#product-images";
    }
    var file = this.files[0];
    var productImg=$(domText);
    //这里我们判断下类型如果不是图片就返回 去掉就可以上传任意文件
    if(!/image\/\w+/.test(file.type)){
        layer.msg("请确保文件为图像类型", {icon: 2});
        return false;
    }
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function(e){
        //验证
        if(file.size/1024>200){	//图片大小限制
            layer.msg("图片不得大于200K.....", {icon: 2});
            return
        }
        imgTxt="<div class='am-u-sm-4 am-margin-bottom-xs'><img  flagImg='-1' class='am-thumbnail' src="+this.result+" alt='展示图片'/><a href='javascript:void(0)' onclick='delImg(this)' class='am-close am-close-alt am-icon-times'></a></div>";//图片存储对象
        productImg.append(imgTxt);//输出
        $("#productFileImg").val("");
        $("#productFileImg2").val("");
    }
};

/*删除商品图片*/
function delImg (othis){
    $(othis).parent().remove();
};
/*新增商品*/
$("#shop-print-add").click(function(){
    resetInput();
    $("#sys-goods-list").collapse('close');
    $("#sys-product-update-model").css("display","block");
});
/*重置模态框*/
function resetInput(){
    $("#sys-product-update-model input").val("");
    $("#sys-product-update-model .deletProduct").val("删除");
    $("#productDetailsIntroduction").val("");
    $("#productDetailsIntroduction2").val("");
    $("#product-images").html("");
    $("#product-images2").html("");
    $("#specProduct").html("");
};
/*非负数限定*/
$("#sys-product-update-model").on("change",".isPositive",function(){
    isPositive(this.value,this);
});
$("#sys-product-update-model").on("keyup",".isPositive",function(){
    isPositive(this.value,this);
});
function isPositive(tet,othis){
    if(tet.substr(0, 1)=="0"){
        $(othis).val("");
        return
    }
    tet=tet.replace(/[^0-9]/g,'');
    $(othis).val(tet);
};
$("#sys-product-update-model").on("change",".isPrice",function(){
    isPrice(this.value,this);
});
function isPrice(tet,othis){
    var objRegExp  = /^[0-9]*$/;
    var tetArr=tet.split('.');
    if(tetArr.length==1){
        if(objRegExp.test(tet)!==true){
            layer.msg("请输入正确的价格", {icon: 2});
            $(othis).val("");
            return
        }else{
            return
        }
    }
    if(tetArr.length == 2 && tetArr[1].length <= 2 ){
        $.each(tetArr,function(index,data){
            if(objRegExp.test(data)!==true){
                layer.msg("请输入正确的价格", {icon: 2});
                $(othis).val("");
            }
        });
    }else{
        layer.msg("最多支持2位小数，请输入正确价格", {icon: 2});
        $(othis).val("");
    }
};